﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Cgd.Shell.Data;

public partial class Links : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{

	}
	protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
	{
		e.Values.Add("Id", Guid.NewGuid());
		using(CgdShellDataContext db = new CgdShellDataContext())
		{
			if (db.Links.Count() > 0)
			{
				int order = db.Links.Max(o => o.DisplayOrder) + 1;
				e.Values.Add("DisplayOrder", order);
			}
			else
			{
				e.Values.Add("DisplayOrder", 0);
			}
		}
	}
	protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
	{
		if(e.CommandName == "cmd:MoveUp")
		{
			MoveUp(new Guid(e.CommandArgument.ToString()));
		}
		else if(e.CommandName == "cmd:MoveDown")
		{
			MoveDown(new Guid(e.CommandArgument.ToString()));
		}
	}

	private void MoveUp(Guid id)
	{
		using (CgdShellDataContext db = new CgdShellDataContext())
		{
			Link l1 = (from l in db.Links
						where l.Id == id
						select l).FirstOrDefault();
			Link l2 = (from l in db.Links
					  where l.DisplayOrder < l1.DisplayOrder
					  orderby l.DisplayOrder descending
					  select l).FirstOrDefault();

			if (l1 != null && l2 != null)
			{
				int order = l1.DisplayOrder;
				l1.DisplayOrder = l2.DisplayOrder;
				l2.DisplayOrder = order;

				db.SubmitChanges();
			}
		}

		Response.Redirect(Request.RawUrl);
	}

	private void MoveDown(Guid id)
	{
		using (CgdShellDataContext db = new CgdShellDataContext())
		{
			Link l1 = (from l in db.Links
					   where l.Id == id
					   select l).FirstOrDefault();
			Link l2 = (from l in db.Links
					   where l.DisplayOrder > l1.DisplayOrder
					   orderby l.DisplayOrder
					   select l).FirstOrDefault();

			if (l1 != null && l2 != null)
			{
				int order = l1.DisplayOrder;
				l1.DisplayOrder = l2.DisplayOrder;
				l2.DisplayOrder = order;

				db.SubmitChanges();
			}
		}

		Response.Redirect(Request.RawUrl);
	}
}
